﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Web.Script.Serialization;

namespace Roberts.MvcExtensions
{
    public static class SerializationExtensions
    {
        public static string ToJSON<T>(this T o, bool useDataContract) where T : class, new()
        {
            string json = "";

            if (useDataContract)
            {
                var serializer = new DataContractJsonSerializer(typeof(T));

                using (var ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, o);
                    json = Encoding.Default.GetString(ms.ToArray());
                    ms.Close();
                }
            }
            else
            {
                var serializer = new JavaScriptSerializer();
                json = serializer.Serialize(o);

            }

            return json;
        }

        public static T FromJSON<T>(this string json, bool useDataContract) where T : class, new()
        {
            if (string.IsNullOrEmpty(json))
            {
                return default(T);
            }

            if (useDataContract)
            {
                var serializer = new DataContractJsonSerializer(typeof(T));
                byte[] byteArray = Encoding.ASCII.GetBytes(json);
                using (var stream = new MemoryStream(byteArray))
                {
                    return serializer.ReadObject(stream) as T;
                }
            }
            else
            {
                var serializer = new JavaScriptSerializer();
                return serializer.Deserialize<T>(json);
            }
        }
    }
}
